(function() {
  window.Droplist = function(field, items) {
    this.field = field;
    if (!$id('droplist-wrapper')) {
      var droplistWrapper = document.createElement('div');
      droplistWrapper.id = 'droplist-wrapper';
      var droplist = document.createElement('ul');
      droplist.id = 'droplist';
      $(droplistWrapper).append(droplist);
      $(document.body).append(droplistWrapper);
    }
    this.setup();

    var that = this;
    if (items && $.type(items) == 'array') {
      items.forEach(function(item) {
        var itemText;
        var itemValue;
        if ($.type(item) == 'string') {
          itemText = itemValue = item;
        } else if ($.type(item) == 'array') {
          itemText = item[0];
          itemValue = item[1];
        }
        that.addItem(itemText, itemValue);
      });
    }
  };
  
  Droplist.prototype = {
    setup: function() {
      var that = this;
      $(this.field).on('click', function(event) {
        event.stopPropagation();
        that.show();
      });

      $('#droplist').on('click', function(event) {
        var target = event.target;
        if (target.tagName == 'LI') {
          var text = that.getText(target);
          var value = $(target).attr('data-path-value');
          that.setSelected(text, value);
        }
        that.hide();
      });

      this.clear();
    },

    addItem: function(itemText, itemValue, toTail) {
      itemValue = itemValue || itemText;
      var li = document.createElement('li');
      $(li).html(itemText).attr('data-path-value', itemValue);
      if (toTail)
        $('#droplist').append(li);
      else
        $('#droplist').prepend(li);
      this.length++;
    },
    
    show: function() {
      this.setDroplistStyle();
      $('#droplist-wrapper').show();
    },

    hide: function() {
      $('#droplist-wrapper').hide();
    },

    remove: function(index) {
      var $removed = $('#droplist > li').get(index);
      $('#droplist').removeChild($removed);
    },
    
    clear: function() {
      $('#droplist').html('');
      this.length = 0;
    },

    setDroplistStyle: function() {
      var field = this.field;
      var width = field.offsetWidth;
      var top = field.offsetHeight + field.offsetTop;
      var left = field.offsetLeft;
      $('#droplist-wrapper').css({
        width: width - 2 + 'px',
        top: top + 'px',
        left: left + 'px'
      });
    },

    getText: function(itemNode) {
      return itemNode.innerText;
    },

    setSelected: function(text, value) {
      $(this.field).text(text);
    }
  };
})();